<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Service\YoppayUtils\YopClient3;
use App\Service\YoppayUtils\YopRequest;
use App\Service\OrderService;
use App\Common\Base;

class MerchantCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:merchantSettle';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'settle merchant order';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {   
        //查找小程序订单，已支付，交易已完成的
        echo "----------------Date:".date('Y-m-d H:i:s')."----------------\n";
        $orders = DB::table('orders')
                    ->where(['type'=> 3, 'payment_status' => 1, 'status' =>3, 'state' => 0])
                    ->get()
                    ->toarray(); 
        $orders = array_map('get_object_vars', $orders); 
        // var_dump($orders);exit();
        foreach ($orders as $key => $order) 
        {
            // 找到相应的订单详情，看发货时间
            $ordersInfo = DB::table('orders_info')
            ->where(['batchcode' => $order['batchcode'] ])
            ->get()
            ->toArray();
            $orders_info = array_map('get_object_vars', $ordersInfo);
            // var_dump($orders_info);exit();
            foreach ($orders_info as $oinfo) 
            { 
                if( $oinfo['pay_batchode'] != null &&
                (time() - strtotime($oinfo['shipping_time']) >= Config('app.settleMerchantTime') ) 
                ){
                    // var_dump($oinfo);exit();
                    DB::beginTransaction();
                    try{
                        $orderConfirmed = OrderService::confirmOrder($oinfo['batchcode'], $oinfo['user_id']);
                        if($orderConfirmed['code'] != 666){
                            echo "-------订单确认失败------".$oinfo['batchcode']."-------".$orderConfirmed['msg']."----".json_encode($orderConfirmed['data'])."-----\n";
                        }
                        DB::commit();
                    }catch(\Exception $exception) {
                        DB::rollBack();
                        echo '-------订单确认失败------'.$oinfo['batchcode']."-------\n";
                    }
                }
            }
            
         } 
    }

}
